package com.randb.nicehttp_compile

import com.randb.nicehttp_annotationprocessor.*
import com.randb.nicehttp_compile.ClassHelper.generateBaseRxHttp
import com.randb.nicehttp_compile.ClassHelper.generatorObservableDownload
import com.randb.nicehttp_compile.ClassHelper.generatorObservableErrorHandler
import com.randb.nicehttp_compile.ClassHelper.generatorObservableHttp
import com.randb.nicehttp_compile.ClassHelper.generatorObservableUpload
import javax.annotation.processing.*
import javax.lang.model.SourceVersion
import javax.lang.model.element.TypeElement
import javax.lang.model.util.Elements
import javax.lang.model.util.Types
import javax.tools.Diagnostic

/**
 *User: RandBII
 *Date: 2020/5/8
 *Description:
 */
class AnnotationProcessor : AbstractProcessor() {

    private lateinit var typeUtils: Types
    private lateinit var messager: Messager
    private lateinit var filer: Filer
    private lateinit var elementUtils: Elements
    private var processed = false


    @Synchronized
    override fun init(processingEnv: ProcessingEnvironment) {
        super.init(processingEnv)
        typeUtils = processingEnv.typeUtils
        messager = processingEnv.messager
        filer = processingEnv.filer
        elementUtils = processingEnv.elementUtils
        val map = processingEnv.options
        initRxJavaVersion(map["NiceHttp-RxJava"])
    }

    override fun getSupportedAnnotationTypes(): MutableSet<String> {
        val annotations: MutableSet<String> = LinkedHashSet()
        annotations.add(Converter::class.java.canonicalName)
        annotations.add(Param::class.java.canonicalName)
        annotations.add(DefaultDomain::class.java.canonicalName)
        annotations.add(Domain::class.java.canonicalName)
        annotations.add(Parser::class.java.canonicalName)
        return annotations
    }

    override fun getSupportedSourceVersion(): SourceVersion {
        return SourceVersion.latestSupported()
    }


    override fun process(
        annotations: MutableSet<out TypeElement>?,
        roundEnv: RoundEnvironment?
    ): Boolean {

        messager.printMessage(
            Diagnostic.Kind.WARNING,
            "processor start  annotations $annotations this =$this"
        )
        if (annotations!!.isEmpty() || processed) return true

        generateBaseRxHttp(filer)
        if (isDependenceRxJava()) { // 如果依赖了rxjava
            generatorObservableErrorHandler(filer)
            generatorObservableHttp(filer)
            generatorObservableUpload(filer)
            generatorObservableDownload(filer)
        }

        try {
            TODO("待完善")
        } catch (e: Exception) {
            e.printStackTrace()
        }




        return false
    }
}